<template>
  <BasicModal :title="getTitle" v-bind="$attrs" @ok="handleSubmit" @register="registerModal">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { computed, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { FormSchemaAdd } from './account.data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { doAdminAdd } from '@/modules/system/api';

  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();

  const isUpdate = ref(true);
  const rowId = ref('0');

  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: FormSchemaAdd,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.adminId;
      await setFieldsValue({
        ...data.record,
      });
      updateSchema([
        {
          field: 'password',
          show: false,
        },
      ]);
    } else {
      rowId.value = '0';
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      doAdminAdd({ ...values, adminId: rowId.value }).then((res) => {
        if (res.code > 0) {
          createMessage.warning(res.message);
          return;
        }
        createMessage.success(res.message);
        closeModal();
        emit('success', { isUpdate: unref(isUpdate), values: { ...values, adminId: rowId.value } });
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
